package com.jbbmobile.hackathon.WebService;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;
import com.jbbmobile.hackathon.Model.Person;
import com.jbbmobile.hackathon.Util.UtilFunc;

public class GetPeople extends HttpServlet {
	private static final long serialVersionUID = 5595508331033708323L;
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		Objectify ob = ObjectifyService.begin();
		PrintWriter printWriter = resp.getWriter();
		double lon = Double.parseDouble(req.getParameter("lon"));
		double lat = Double.parseDouble(req.getParameter("lat"));
		Query<Person> personsLon = ob.query(Person.class).filter("longtitude >=", lon + UtilFunc.RADIUS).
			filter("longtitude <=", lat - UtilFunc.RADIUS);
		List<Person> personsLat = ob.query(Person.class).filter("latitude >=", lat + UtilFunc.RADIUS).
			filter("latitude <=", lat - UtilFunc.RADIUS).list();
		List<Person> persons = new ArrayList<Person>();
		for (Person p : personsLon) 
			if (personsLat.contains(p)) 
				persons.add(p);
		printWriter.println("<Persons>");
		for (Person p : persons) {
			printWriter.write(
				"<Person>" + 
					"<Id>" + p.getType() + "</Id>" +
					"<Name>" + p.getName() + "</Name>" +
					"<Lon>" + p.getLongtitude() + "</Lon>" +
					"<Lat>" + p.getLatitude() + "</Lat>" + 
				"</Person>");
		} 
		printWriter.println("</Persons>");
	}
}
